package com.ukao.cashregister.ui.vipManager;


import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.TextView;

import com.bigkoo.pickerview.TimePickerView;
import com.ukao.cashregister.R;
import com.ukao.cashregister.adapter.KeyboardAdapter;
import com.ukao.cashregister.base.MvpFragment;
import com.ukao.cashregister.bean.VipGroupBean;
import com.ukao.cashregister.bean.VipLeverBean;
import com.ukao.cashregister.consts.GlobalConsts;
import com.ukao.cashregister.consts.SaveParamets;
import com.ukao.cashregister.dialog.ChooseTimeDialogFragment;
import com.ukao.cashregister.dialog.DialogTool;
import com.ukao.cashregister.eventbus.ChooseTimeEvent;
import com.ukao.cashregister.listener.OnItemClickListener;
import com.ukao.cashregister.pesenter.BuiltVipPesenter;
import com.ukao.cashregister.utils.CheckUtils;
import com.ukao.cashregister.utils.KeyBoardUtil;
import com.ukao.cashregister.utils.L;
import com.ukao.cashregister.utils.RegularUtils;
import com.ukao.cashregister.utils.T;
import com.ukao.cashregister.view.CreateVipView;
import com.ukao.cashregister.widget.ClearEditText;

import org.greenrobot.eventbus.Subscribe;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

import static com.ukao.cashregister.R.id.et_phone;
import static com.ukao.cashregister.R.id.vip_card;
import static com.ukao.cashregister.utils.MyDateUtils.getTime;

/**
 * 新建会员
 */
public class CreateVipFragment extends MvpFragment<BuiltVipPesenter> implements CreateVipView {


    Unbinder unbinder;
    @BindView(R.id.key_recycler_view)
    RecyclerView keyRecyclerView;
    @BindView(R.id.print_order)
    Button printOrder;
    @BindView(et_phone)
    ClearEditText phoneInput;  //电话
    @BindView(R.id.clean_button)
    Button cleanButton;
    @BindView(R.id.et_name)
    ClearEditText nameInput;
    @BindView(R.id.man)
    RadioButton man;
    @BindView(R.id.girl)
    RadioButton girl;
    @BindView(R.id.vip_card)
    Button vipCard;
    @BindView(R.id.btn_birthdate)
    Button birthdateBtn;  //出生日期按钮
    @BindView(R.id.grouping)
    Button grouping;
    @BindView(R.id.back)
    TextView back;


    private KeyboardAdapter mKeyboardAdapter;
    private String timeType = "yyyy-MM-dd";
    private ArrayList<VipGroupBean> mvipGroupData;
    private ArrayList<VipLeverBean.ListBean> mvipleverData;
    private VipLeverBean.ListBean mseletlever;
    private VipGroupBean mSelectGroup;
    private String cardId = "";
    private String groupId = "";
    private String birthday;
    private String strPhone;
    private String strName;
    private String msex;
    private ArrayList<VipLeverBean.ListBean> mvipleverDatas;
    private ArrayList<VipGroupBean> mvipGroupDatas;
    private String phone;
    public static CreateVipFragment newInstance(Serializable param1, Serializable param2) {
        CreateVipFragment fragment = new CreateVipFragment();
        Bundle args = new Bundle();
        args.putSerializable(ARG_PARAM1, param1);
        args.putSerializable(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    public static CreateVipFragment newInstance(String phone) {
        CreateVipFragment fragment = new CreateVipFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM3, phone);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            phone = getArguments().getString(ARG_PARAM3);
            mvipGroupData = new ArrayList<VipGroupBean>();
            mvipleverData = new ArrayList<VipLeverBean.ListBean>();
            if (null == phone) {
                mvipGroupDatas = (ArrayList<VipGroupBean>) getArguments().getSerializable(ARG_PARAM1);
                if (!CheckUtils.isEmpty(mvipGroupDatas)) {
                    mvipGroupData.addAll(mvipGroupDatas);
                    mvipGroupData.remove(0);
                }
                mvipleverDatas = (ArrayList<VipLeverBean.ListBean>) getArguments().getSerializable(ARG_PARAM2);
                if (!CheckUtils.isEmpty(mvipleverDatas)) {
                    mvipleverData.addAll(mvipleverDatas);
                    mvipleverData.remove(0);
                }
            }
        }
    }

    @Override
    protected BuiltVipPesenter createPresenter() {
        return new BuiltVipPesenter(this);
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_built_vip, container, false);
        unbinder = ButterKnife.bind(this, view);
        initView();
        initListener();
        return view;
    }

    @Override
    protected void initView() {

        if (phone != null) {
            phoneInput.setText(phone);
            mvpPresenter.vipUserLever(_mActivity);
        }
        if (!CheckUtils.isNull(mvipGroupData)) {
            for (VipGroupBean vipGroupBean : mvipGroupData) {
                vipGroupBean.setCheck(false);
            }
        }
        setDefaultChecked();
        phoneInput.requestFocus();
        KeyBoardUtil.showKeyboard(phoneInput);
        birthdateBtn.setText(R.string.please_select);
        // birthdateBtn.setText(MyDateUtils.formatDate(MyDateUtils.getDateYearsago()));
        String[] keyBoardData = getResources().getStringArray(R.array.vip_keyboard);
        initGridRecyclerView(keyRecyclerView, 3);
        mKeyboardAdapter = new KeyboardAdapter(activity, Arrays.asList(keyBoardData));
        mKeyboardAdapter.setIsVipEnter(true);
        keyRecyclerView.setAdapter(mKeyboardAdapter);
    }

    private void setDefaultChecked() {
        if (!CheckUtils.isEmpty(mvipleverData) && !CheckUtils.isEmpty(mvipGroupData)) {
            for (VipLeverBean.ListBean listBean : mvipleverData) {
                if (listBean.getDef()) {
                    vipCard.setText(listBean.getName());
                    cardId = listBean.getId();
                    listBean.setCheck(true);
                } else {
                    listBean.setCheck(false);
                }
            }
            VipGroupBean mitem = mvipGroupData.get(0);
            groupId = mitem.getId();
            grouping.setText(mitem.getName());
            mitem.setCheck(true);
        }
    }

    @Override
    protected void initListener() {
        super.initListener();
        mKeyboardAdapter.setOnClickListener(mOnItemClickListener);
    }

    @Override
    public boolean onBackPressedSupport() {
        return super.onBackPressedSupport();
    }

    @Override
    protected boolean useEventBus() {
        return true;
    }

    @Subscribe
    public void onEvent(ChooseTimeEvent event) {
        switch (event.getMessage()) {
            case groud:
                mSelectGroup = (VipGroupBean) event.getData();
                grouping.setText(mSelectGroup.getName());
                groupId = mSelectGroup.getId();
                break;
            case lever:
                mseletlever = (VipLeverBean.ListBean) event.getData();
                vipCard.setText(mseletlever.getName());
                cardId = mseletlever.getId();
                break;
        }
    }

    private OnItemClickListener mOnItemClickListener = new OnItemClickListener() {
        @Override
        public void onSureItemClick(Object item, int pos) {
            if (pos != 10 && pos != 11) {
                String message = (String) item;
                String strgatherNum = phoneInput.getText().toString().trim();
                strgatherNum += message;
                phoneInput.setText(strgatherNum);
            }
            switch (pos) {
                case 10:
                    String removeGatherNum = phoneInput.getText().toString().trim();
                    if (!CheckUtils.isEmpty(removeGatherNum))
                        phoneInput.setText(removeGatherNum.substring(0, removeGatherNum.length() - 1));
                    break;
                case 11:  /*确定*/
                    nameInput.setSelection(nameInput.getText().length());
                    break;
            }
        }
    };


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.print_order, R.id.clean_button, R.id.btn_birthdate, vip_card, R.id.grouping, R.id.back, R.id.et_phone})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.et_phone:
                nameInput.clearFocus();
                break;

            case R.id.back:
                if (CheckUtils.isEmpty(phone)) {
                    setFragmentResult(RESULT_OK, null);

                }
                finish();
                break;
            case R.id.print_order:  /*确定*/
                strPhone = getText(phoneInput);
                strName = getText(nameInput);
                birthday = getText(birthdateBtn);
                String strvipCard = getText(vipCard);
                msex = "";
                if (!RegularUtils.isMobileSimple(strPhone)) {
                    T.show("请输入正确手机号");
                    return;
                } else if (strName.isEmpty()) {
                    T.show("请输入名字");
                    return;
                } else if (strvipCard.isEmpty()) {
                    T.show("请选择会员卡");
                    return;
                } else if (!man.isChecked() && !girl.isChecked()) {
                    T.show("请输入选择性别");
                    return;
                }

                if (man.isChecked()) {
                    msex = "1";
                } else {
                    msex = "2";
                }
                saveViPName();

                break;
            case R.id.clean_button:
                phoneInput.setText("");
                break;
            case R.id.btn_birthdate:   //请选择
                String birthday = birthdateBtn.getText().toString();
                birthday = birthday.equals(getString(R.string.please_select)) ? "" : birthday;
                DialogTool.getSingleton().showDatePicker(birthday, timeType, activity, mOnTimeSelectListener);
                break;
            case R.id.grouping:  //分组
                ChooseTimeDialogFragment chooseTime = new ChooseTimeDialogFragment();
                Bundle bundle = new Bundle();
                bundle.putString("Type", GlobalConsts.VIP_GROUND_ENTER);
                bundle.putSerializable("chooseTime", mvipGroupData);
                chooseTime.setArguments(bundle);
                chooseTime.show(getChildFragmentManager(), GlobalConsts.VIP_GROUND_ENTER);
                break;
            case R.id.vip_card:     //普通会员卡
                ChooseTimeDialogFragment vipDialog = new ChooseTimeDialogFragment();
                Bundle vipBundle = new Bundle();
                vipBundle.putString("Type", GlobalConsts.VIP_LEVER_ENTER);
                vipBundle.putSerializable("chooseTime", mvipleverData);
                vipDialog.setArguments(vipBundle);
                vipDialog.show(getChildFragmentManager(), GlobalConsts.VIP_LEVER_ENTER);
                break;


        }
    }


    private void saveViPName() {
        HashMap mHashMap = new HashMap<String, String>();
        mHashMap.put("accessToken", SaveParamets.getToken(_mActivity));
        mHashMap.put("name", strName);
        mHashMap.put("phone", strPhone);
        mHashMap.put("sex", msex);
        mHashMap.put("cardId", cardId + "");
        mHashMap.put("birthday", birthday.equals("请选择") ? "" : birthday);
        mHashMap.put("groupId", groupId);
        mvpPresenter.saveViPName(mHashMap);
        L.i("mHashMap=" + mHashMap.toString());
    }


    private TimePickerView.OnTimeSelectListener mOnTimeSelectListener = new TimePickerView.OnTimeSelectListener() {
        @Override
        public void onTimeSelect(Date date, View v) {
            birthdateBtn.setText(getTime(date, timeType));

        }
    };

    @Override
    public void loadFailure(String message) {
        T.show(message);
    }

    @Override
    public void loadVipLeverSucceed(List<VipLeverBean.ListBean> mvipleverBean) {
        mvipleverData.addAll(mvipleverBean);
        mvipleverData.remove(0);
    }

    @Override
    public void buildUserSucceed() {
        Bundle bundle = new Bundle();
        if (phone == null) {
            bundle.putString("phone", "");
            bundle.putString("groupId", groupId);
        } else {
            bundle.putString("phone", strPhone);
        }
        setFragmentResult(RESULT_OK, bundle);
        finish();
    }

    @Override
    public void loadvipGroupSucceed(List<VipGroupBean> allSserGroup) {
        mvipGroupData.addAll(allSserGroup);

    }
    @Override
    public void loadAllPacketSucceed(List<VipGroupBean> mallSserGroup) {
        mvipGroupData.addAll(mallSserGroup);
        setDefaultChecked();
    }


}
